/*
 * @(#)MaintUserRecordAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.user.web;

import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.bean.DmsPersonalStorageSetup;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.core.DmsPersonalStorageSetupManager;
import com.dcivision.dms.dao.DmsPersonalStorageSetupDAObject;
import com.dcivision.dms.dao.DmsRootDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.staff.bean.StaffRecord;
import com.dcivision.staff.dao.StaffRecordDAObject;
import com.dcivision.user.bean.MtmUserRecordUserGroup;
import com.dcivision.user.bean.MtmUserRecordUserRole;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserMember;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.core.UserManager;
import com.dcivision.user.dao.MtmUserRecordUserGroupDAObject;
import com.dcivision.user.dao.MtmUserRecordUserRoleDAObject;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.user.dao.UserRoleDAObject;
import com.dcivision.workflow.dao.MtmWorkflowDynamicUserActorDAObject;
import com.dcivision.workflow.dao.MtmWorkflowStepUserActorDAObject;

/**
  MaintUserRecordAction.java

  This class is for maint user record.

    @author          Rollo Chan
    @company         DCIVision Limited
    @creation date   26/06/2003
    @version         $Revision: 1.46.2.2 $
*/

/* ********************************Modify History***********************************************
 * Modify by  : Jicle.Wang 
 * Modify date: 2006/06/12
 * Description: Show data in .jsp to Copy
 * *********************************************************************************************
 */
 
public class MaintUserRecordAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.46.2.2 $";

  public MaintUserRecordAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.user.dao.UserRecordDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.SETUP_USER_ACCOUNT);
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    UserRoleDAObject userRoleDAO = new UserRoleDAObject(this.getSessionContainer(request), this.getConnection(request));
    request.setAttribute("allRoleList", userRoleDAO.getFullList());

    UserGroupDAObject userGroupDAO = new UserGroupDAObject(this.getSessionContainer(request), this.getConnection(request));
    request.setAttribute("allGroupList", userGroupDAO.getPublicGroupList());

    return super.execute(mapping, form, request, response);
  }
  
  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    super.selectRecord(mapping, form, request, response);

    MaintUserRecordForm userRecordForm = (MaintUserRecordForm)form;

    UserGroupDAObject userGroupDAO = new UserGroupDAObject(this.getSessionContainer(request), this.getConnection(request));
    List listGroup = userGroupDAO.getListByUserRecordIDGroupType(new Integer(userRecordForm.getID()), UserGroup.GROUP_TYPE_PUBLIC);
    try {
      Integer[] iaGroupID = (Integer[])Utility.getPropertyArray(listGroup, "ID", new Integer[0]);
      String[] saGroupID = Utility.getStringArray(iaGroupID);
      userRecordForm.setUserGroups(saGroupID);
    } catch (Exception e) {
      log.error("Retrieve Group ID list.", e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }

    UserRoleDAObject userRoleDAO = new UserRoleDAObject(this.getSessionContainer(request), this.getConnection(request));
    List listRole = userRoleDAO.getListByUserRecordID(new Integer(userRecordForm.getID()));
    try {
      Integer[] iaRoleID = (Integer[])Utility.getPropertyArray(listRole, "ID", new Integer[0]);
      String[] saRoleID = Utility.getStringArray(iaRoleID);
      userRecordForm.setUserRoles(saRoleID);
    } catch (Exception e) {
      log.error("Retrieve Role ID list.", e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }

    if ( !Utility.isEmpty(userRecordForm.getUserLinkID()) ) {
    	try{
    		StaffRecordDAObject staffRecordDAO = new StaffRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
      	StaffRecord staffRecord = (StaffRecord)staffRecordDAO.getObjectByID(TextUtility.parseIntegerObj(userRecordForm.getUserLinkID()));
      	userRecordForm.setUserType("E");
    	} catch (Exception ex){
    		userRecordForm.setUserType("S");
  			userRecordForm.setFirstName("");
  			userRecordForm.setLastName("");
  			userRecordForm.setFullName("");
  			userRecordForm.setEmail("");
    	}
    }
  }

  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintUserRecordForm userRecordForm = (MaintUserRecordForm)form;
    String userType = userRecordForm.getUserType();

    //set User Record
    UserRecord userRecord = new UserRecord();
    UserRecord newUser = null;
    userRecord.setEmail(userRecordForm.getEmail());
    userRecord.setFirstName(userRecordForm.getFirstName());
    userRecord.setLastName(userRecordForm.getLastName());
    userRecord.setFullName(userRecordForm.getFullName());
    userRecord.setLoginName(userRecordForm.getLoginName());
    userRecord.setLoginPwd(userRecordForm.getLoginPwd());
    userRecord.setModifyLoginPwd(userRecordForm.getModifyLoginPwd());
    userRecord.setMaxAttempt(TextUtility.parseIntegerObj(userRecordForm.getMaxAttempt()));
    userRecord.setPreference(TextUtility.parseIntegerObj(userRecordForm.getPreference()));
    userRecord.setPwdExpiryDay(TextUtility.parseIntegerObj(userRecordForm.getPwdExpiryDay()));
    userRecord.setFailedAttempt(TextUtility.parseIntegerObj(userRecordForm.getFailedAttempt()));
    userRecord.setUserType(userRecordForm.getUserType());
    userRecord.setStatus(userRecordForm.getStatus());
    userRecord.setLocale(userRecordForm.getLocale());
    userRecord.setUserDef1(userRecordForm.getUserDef1());
    userRecord.setUserDef2(userRecordForm.getUserDef2());
    userRecord.setUserDef3(userRecordForm.getUserDef3());
    userRecord.setUserDef4(userRecordForm.getUserDef4());
    userRecord.setUserDef5(userRecordForm.getUserDef5());
    userRecord.setUserLinkID(TextUtility.parseIntegerObj(userRecordForm.getUserLinkID()));
    String[] userRoleID = userRecordForm.getUserRoles();
    String[] userGroupIDs = userRecordForm.getUserGroups();

    UserManager userManager = new UserManager(this.getSessionContainer(request),this.getConnection(request));
    newUser = userManager.createUser(userRecord,userRoleID,userGroupIDs);
    if (newUser!= null){
    	userRecordForm.setID(newUser.getID().toString());
      userRecordForm.setUserLinkID(newUser.getUserLinkID().toString());
    }
  }

  
  /**
   * 
   * Validate selected staff record of current user record,<br>
   * avoid the selected staff belong to an existing user.<br>
   *
   * @param  form     current selected form record for edit
   * @param  request  
   * @throws ApplicationException
   * @author Bill add for EIP-872
   */ 
  public void validateUserByUserLinkID(ActionForm form,HttpServletRequest request)throws ApplicationException{
	MaintUserRecordForm userRecord=(MaintUserRecordForm)form;
	String currentStaffIdOfUser=userRecord.getUserLinkID();
	String currentUserID=userRecord.getID();
    UserRecordDAObject userRecordDAO=new UserRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
    if(!Utility.isEmpty(currentStaffIdOfUser) && !Utility.isEmpty(currentUserID)){
      boolean isTheStaffBelongToOtherUser=userRecordDAO.isStaffIDHasChecked(currentStaffIdOfUser, new Integer(currentUserID));
      if(!isTheStaffBelongToOtherUser){
        throw new ApplicationException(ErrorConstant.USER_MESSAGE_DUPLICATE_STAFF);
      }
    }
    
  }
  
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
	MaintUserRecordForm userRecordForm = (MaintUserRecordForm)form;    
    Integer userRecordID = new Integer(userRecordForm.getID());
    String selectedUserType = userRecordForm.getUserType();
//    if ( selectedUserType.indexOf("S")==0 ) {
      if ( userRecordForm.getUserType().equals("S") ) {          // new staff
        StaffRecord staffRecord = null;
        staffRecord = createStaffRecord(userRecordForm , request);
        userRecordForm.setUserLinkID(staffRecord.getID().toString());

      } else if ( selectedUserType.equals("E") ) {  // existing staff
        if ( Utility.isEmpty(userRecordForm.getUserLinkID()) ) {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        } else {
          SessionContainer sessionCon = this.getSessionContainer(request);
          Connection conn = this.getConnection(request);
          StaffRecordDAObject dao = new StaffRecordDAObject(sessionCon, conn);
          try {
          	Object obj = dao.getObjectByID(new Integer(userRecordForm.getUserLinkID()));
          } catch(ApplicationException appEx){
          	throw new ApplicationException(ErrorConstant.USER_MESSAGE_NOT_FOUND_STAFF);
          }
          //Object obj = dao.getObjectByID(new Integer(userRecordForm.getUserLinkID()));
          ((MaintUserRecordForm)form).setUserType("S");
        }
      }
//    } else if ( userRecordForm.getUserType().indexOf("C")==0 ) {
//    }
    if(userRecordForm.getStatus().equals(GlobalConstant.STATUS_ACTIVE)){
      userRecordForm.setFailedAttempt("0");
    }
    super.updateRecord(mapping, form, request, response);

    //Restore the original selected user type for correct display of "New Staff" / "Existing Staff"
    userRecordForm.setUserType(selectedUserType);

    MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAO = new MtmUserRecordUserRoleDAObject(this.getSessionContainer(request), this.getConnection(request));
    DmsPersonalStorageSetupManager dmsPersonalStorageSetupManager=new DmsPersonalStorageSetupManager(this.getSessionContainer(request),this.getConnection(request));
    DmsPersonalStorageSetupDAObject dmsPersonalStorageSetupDAO=new DmsPersonalStorageSetupDAObject(this.getSessionContainer(request),this.getConnection(request));
    DmsRootDAObject dmsRootDAO=new DmsRootDAObject(this.getSessionContainer(request),this.getConnection(request));

    // Delete the old user roles belonging to the user record
    mtmUserRecordUserRoleDAO.deleteListByUserRecordID(userRecordID);
    // Insert the new user roles belonging to the user record.
    if (!Utility.isEmpty(userRecordForm.getUserRoles())) {
      for (int i=0; i < userRecordForm.getUserRoles().length; i++) {
        MtmUserRecordUserRole mtmRoleBean = new MtmUserRecordUserRole();
        mtmRoleBean.setUserRecordID(new Integer(userRecordForm.getID()));
        mtmRoleBean.setUserRoleID(new Integer(userRecordForm.getUserRoles()[i]));
        mtmUserRecordUserRoleDAO.insertObject(mtmRoleBean);
      }
    }

    MtmUserRecordUserGroupDAObject mtmUserRecordUserGroupDAO = new MtmUserRecordUserGroupDAObject(this.getSessionContainer(request), this.getConnection(request));
    // Delete the old user groups belonged to the user record
    mtmUserRecordUserGroupDAO.deleteListByUserRecordID(userRecordID);
    // Insert the new user groups belonging to the user record.
    if (!Utility.isEmpty(userRecordForm.getUserGroups())) {
      for (int i=0; i < userRecordForm.getUserGroups().length; i++) {
        MtmUserRecordUserGroup mtmGroupBean = new MtmUserRecordUserGroup();
        mtmGroupBean.setUserRecordID(new Integer(userRecordForm.getID()));
        mtmGroupBean.setUserGroupID(new Integer(userRecordForm.getUserGroups()[i]));
        mtmUserRecordUserGroupDAO.insertObject(mtmGroupBean);
      }
      if(!dmsPersonalStorageSetupManager.checkHasStorageUser(userRecordID) && !dmsPersonalStorageSetupManager.checkHasStorageRole(userRecordID)){
        List storageList=dmsPersonalStorageSetupDAO.getStorageGroupListByUserID(userRecordID);
        if(storageList.size()>0){
          DmsPersonalStorageSetup dmsPersonalStorageSetup=(DmsPersonalStorageSetup)storageList.get(0);
          DmsRoot dmsRoot=dmsRootDAO.getPersonalRootByOwnerIDAndType(userRecordID,GlobalConstant.RECORD_STATUS_ACTIVE);
          dmsRoot.setStorageLimit(dmsPersonalStorageSetup.getStorageLimit());
          dmsRoot=(DmsRoot)dmsRootDAO.updateObject(dmsRoot);
        }
      }
    }
    if(!Utility.isEmpty(userRecordForm.getUserRoles())){
      if(!dmsPersonalStorageSetupManager.checkHasStorageUser(userRecordID)){
        List storageList= dmsPersonalStorageSetupDAO.getStorageRoleListByUserID(userRecordID);
        if(storageList.size()>0){
          DmsPersonalStorageSetup dmsPersonalStorageSetup=(DmsPersonalStorageSetup)storageList.get(0);
          DmsRoot dmsRoot=dmsRootDAO.getPersonalRootByOwnerIDAndType(userRecordID,GlobalConstant.RECORD_STATUS_ACTIVE);
          dmsRoot.setStorageLimit(dmsPersonalStorageSetup.getStorageLimit());
          dmsRoot=(DmsRoot)dmsRootDAO.updateObject(dmsRoot);
        }
      }
    }

    // Update UserInfoFactory entry.
    UserInfoFactory.updateUserInfo(new Integer(userRecordForm.getID()), new String[]{userRecordForm.getFullName(), userRecordForm.getEmail()});
  }

  public void deleteRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
	MaintUserRecordForm userRecordForm = (MaintUserRecordForm)form;
	//simon_add_S
	String SuserRecordID=userRecordForm.getID();
  	if (!Utility.isEmpty(SuserRecordID)){
  	  //UserRecordDAObject userDAO = new UserRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
  	  Integer userRecordID=TextUtility.parseIntegerObj(SuserRecordID);
	  //UserRecord userRecord = (UserRecord)userDAO.getObjectByID(userRecordID);
	  if(this.getSessionContainer(request).getUserRecordID().equals(userRecordID)){
		throw new ApplicationException("common.message.cannot_deleted_yourself");
	  }else{
  	    MtmWorkflowStepUserActorDAObject mtmWorkflowStepActorDAO=new MtmWorkflowStepUserActorDAObject(this.getSessionContainer(request), this.getConnection(request));
  	    MtmWorkflowDynamicUserActorDAObject dynamicUserActorDAO=new MtmWorkflowDynamicUserActorDAObject(this.getSessionContainer(request), this.getConnection(request));
  	    List userList=mtmWorkflowStepActorDAO.getListWorkflowStepIDByActorIDAndActorType(userRecordID,UserMember.MEMBER_TYPE_USER);
  	    List dynamicUserList=dynamicUserActorDAO.getListWorkflowStepIDByActorIDAndActorType(userRecordID,UserMember.MEMBER_TYPE_USER);
  	    if (Utility.isEmpty(userList) && Utility.isEmpty(dynamicUserList)){ 			
  		  super.deleteRecord(mapping, form, request, response);

  		  if (userRecordForm.getDeleteStaff().equals("true")) {
  		    UserRecordDAObject  dao = (UserRecordDAObject)getMajorDAObject(request);
  		    dao.deleteRelatedStaffRecord(userRecordID);
  		  }
  		  MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAO = new MtmUserRecordUserRoleDAObject(this.getSessionContainer(request), this.getConnection(request));
  		  // Delete the old user roles belonged to the user record
  		  mtmUserRecordUserRoleDAO.deleteListByUserRecordID(userRecordID);

  		  MtmUserRecordUserGroupDAObject mtmUserRecordUserGroupDAO = new MtmUserRecordUserGroupDAObject(this.getSessionContainer(request), this.getConnection(request));
  		  // Delete the old user groups belonged to the user record
  		  mtmUserRecordUserGroupDAO.deleteListByUserRecordID(userRecordID);
  	    }else{
  		  throw new ApplicationException("common.message.cannot_deleted_record_operation_aborted");
  	    }
	  }
  	}else{
  	  throw new ApplicationException("common.message.cannot_deleted_record_operation_aborted");
  	}
	//simon_add_E
  }

/* Jicle.Wang 2006/06/12 Start */
  //public void clearUniqueFields(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    //MaintUserRecordForm userRecordForm = (MaintUserRecordForm)form;
    //userRecordForm.setUserType(null);
    //userRecordForm.setUserLinkID(null);
    //userRecordForm.setFirstName(null);
    //userRecordForm.setLastName(null);
    //userRecordForm.setFullName(null);
    //userRecordForm.setEmail(null);
    //userRecordForm.setLoginName(null);
  //}
/* Jicle.Wang 2006/06/12 End   */

  /**
   * create a new staff record according to the information in the userRecordForm
   *
   * @param  userRecordForm
   * @param  request
   * @return StaffRecord
   * throws  ApplicationException
   */
  private StaffRecord createStaffRecord(MaintUserRecordForm userRecordForm, HttpServletRequest request) throws ApplicationException {
    SessionContainer sessionCon = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    StaffRecordDAObject dao = new StaffRecordDAObject(sessionCon, conn);
    StaffRecord staffRecord = new StaffRecord();

    staffRecord.setFirstName(userRecordForm.getFirstName());
    staffRecord.setLastName(userRecordForm.getLastName());
    staffRecord.setFullName(userRecordForm.getFullName());
    staffRecord.setEmail(userRecordForm.getEmail());

    staffRecord.setGender("M");
    staffRecord.setSalutationID(new Integer(1));
    staffRecord.setStaffCode("N/A");
    staffRecord.setStatus("A");

    staffRecord = (StaffRecord)dao.insertObject(staffRecord);
    return staffRecord;
  }

}